package com.haiyi.software.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.util.EncodingUtils;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ActivityManager;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.haiyi.software.app.MainApplication;
import com.haiyi.software.app.R;
import com.haiyi.software.entity.EntityMsg;
import com.haiyi.software.entity.EntityMsgGif;
import com.haiyi.software.entity.EntityMsgImage;
import com.haiyi.software.entity.EntityMsgText;
import com.haiyi.software.entity.EntityMsgVoice;
import com.haiyi.software.entity.UserInfo;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class MyTools {

	private static MyTools myToolsInstance = null;

	private static final Pattern EMOTION_URL = Pattern.compile("\\[(\\S+?)\\]");

	private static final String str_server = MainApplication.getInstance()
			.getResources().getString(R.string.URL);

	private static final String str_requestNameDownload = "down.php";

	private JsonElement jsonDownloadReturn;

	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式

	private static MediaPlayer mMediaPlayer;

	private static MediaPlayer getMediaPlayer() {

		if (mMediaPlayer == null) {
			mMediaPlayer = new MediaPlayer();
		}
		return mMediaPlayer;

	}

	public static MyTools getInstance() {

		if (myToolsInstance == null) {
			myToolsInstance = new MyTools();
		}
		return myToolsInstance;
	}

	/**
	 * 获取下载附件的返回值
	 * 
	 * @return JsonElement
	 */
	public JsonElement getJsonDownloadReturn() {
		return jsonDownloadReturn;
	}

	/**
	 * 根据附件的ID下载附件（信息）
	 * 
	 * @param attuid
	 */
	public synchronized void downLoadFileByAttuid(String attuid,
			final Handler handler) {

		AsyncHttpClient client = MainApplication.getInstance()
				.getAsyncHttpClient();

		RequestParams params = new RequestParams();

		params.put("args", getDownloadJsonArgs(attuid));

		client.setTimeout(60);

		L.i("serverURL", str_server + str_requestNameDownload + "");

		client.post(str_server + str_requestNameDownload, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] responseBody) {
						// TODO 自动生成的方法存根
						try {
							String str_jsonReturn = new String(responseBody,
									"UTF-8");

							L.i("rbody", str_jsonReturn);

							JsonParser parse = new JsonParser();

							jsonDownloadReturn = parse.parse(str_jsonReturn);

							handler.sendEmptyMessage(1);

						} catch (Exception e) {
							// TODO 自动生成的 catch 块
							e.printStackTrace();
						}

						// Log.i("success", statusCode + "");
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						// TODO 自动生成的方法存根
						handler.sendEmptyMessage(0);

					}
				});

	}

	/**
	 * 获取下载文件时需要提供的参数，JSON字符串
	 * 
	 * @param attuid
	 *            附件ID
	 * @return JSON字符串
	 */
	private String getDownloadJsonArgs(String attuid) {

		UserInfo myInfo = MainApplication.getInstance().getMineUserInfo();

		if (myInfo != null) {
			Map<String, Object> validator = new HashMap<String, Object>();

			validator.put("uid", myInfo.getUid());
			validator.put("uname", myInfo.getUname());
			validator.put("pwd", myInfo.getPwd());
			validator.put("uguid", myInfo.getUguid());

			Map<String, Object> body = new HashMap<String, Object>();
			body.put("attuid", attuid);

			Map<String, Object> args = new HashMap<String, Object>();
			args.put("validator", validator);
			args.put("body", body);

			Gson gson = new Gson();
			String s = gson.toJson(args);

			return s;

		} else {
			return "";
		}

	}

	public void downLoadFileByFilePath(String fileServerPath,
			final int fileType, final String fileNewLocalPath,
			final Handler handler) {

		AsyncHttpClient client = MainApplication.getInstance()
				.getAsyncHttpClient();

		client.get(str_server + fileServerPath, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {
				// TODO 自动生成的方法存根

				switch (fileType) {
				case 1:

					try {

						// TODO:异步!!
						FileOutputStream fout = new FileOutputStream(
								fileNewLocalPath);
						fout.write(responseBody);
						fout.flush();
						fout.close();
						// TODO:异步!!

						playMusic(fileNewLocalPath);

						handler.sendEmptyMessage(1);

					} catch (FileNotFoundException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
					break;
				}

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				// TODO 自动生成的方法存根

			}
		});
	}

	/*
	 * 返回位置信息
	 */
	public Location getLocation() {

		LocationManager manager = (LocationManager) MainApplication
				.getInstance().getSystemService(
						MainApplication.getInstance().LOCATION_SERVICE);// 获取手机位置信息
		// // 获取的条件
		// Criteria criteria = new Criteria();
		// criteria.setAccuracy(Criteria.ACCURACY_FINE);// 获取精准位置
		// criteria.setCostAllowed(true);// 允许产生开销
		// criteria.setPowerRequirement(Criteria.POWER_HIGH);// 消耗大的话，获取的频率高
		// criteria.setSpeedRequired(true);// 手机位置移动
		// criteria.setAltitudeRequired(true);// 海拔
		//
		// // 获取最佳provider: 手机或者模拟器上均为gps
		// String bestProvider = manager.getBestProvider(criteria, true);//
		// 使用GPS卫星
		//
		// System.out.println("最好的位置提供者是" + bestProvider);

		// parameter: 1. provider 2. 每隔多少时间获取一次 3.每隔多少米 4.监听器触发回调函数
		// manager.requestLocationUpdates(bestProvider, 60000, 100, new
		// MyLocationListener());

		// Location location = manager.getLastKnownLocation(bestProvider);
		Location location = manager
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		// while (location == null) {
		// manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
		// 6000, 1, mLocationListener);
		// }
		return location;
	}

	/**
	 * 根据消息中的接收者，返回接收人的UID
	 * 
	 * @param fromString
	 * @return
	 */
	public static String getMessageHiid(String fromString) {

		if (fromString != null) {
			String[] sps = fromString.split("@");

			return sps[0];
		} else {
			return "";
		}

	}

	/*
	 * 生成数据库的名字
	 */
	// public static String getDBName(Context context) {
	//
	//
	//
	// return dbName;
	// }

	/**
	 * 获取文件的MD5值
	 * 
	 * @param file
	 * @return
	 */
	public static String getMd5ByFile(File file) {
		String value = null;
		FileInputStream in = null;
		try {

			in = new FileInputStream(file);
			MappedByteBuffer byteBuffer = in.getChannel().map(
					FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return value;
	}

	/**
	 * 从InputStream中获取字符串
	 * 
	 * @return
	 */
	public static String getStringFromInputStream(InputStream in) {
		String result = "";
		try {

			// 获取文件的字节数
			int lenght = in.available();
			// 创建byte数组
			byte[] buffer = new byte[lenght];
			// 将文件中的数据读到byte数组中
			in.read(buffer);
			result = EncodingUtils.getString(buffer, "Encoding.UTF_8");
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 处理字符串中的表情
	 * 
	 * @param context
	 * @param message
	 *            传入的需要处理的String
	 * @param small
	 *            是否需要小图片
	 * @return
	 */
	public static CharSequence convertNormalStringToSpannableString(
			Context context, String message, boolean small) {
		String hackTxt;
		if (message.startsWith("[") && message.endsWith("]")) {
			hackTxt = message + " ";
		} else {
			hackTxt = message;
		}
		SpannableString value = SpannableString.valueOf(hackTxt);

		Matcher localMatcher = EMOTION_URL.matcher(value);
		while (localMatcher.find()) {
			String str2 = localMatcher.group(0);
			int k = localMatcher.start();
			int m = localMatcher.end();
			if (m - k < 8) {
				if (MainApplication.getInstance().getFaceMap()
						.containsKey(str2)) {
					int face = MainApplication.getInstance().getFaceMap()
							.get(str2);
					Bitmap bitmap = BitmapFactory.decodeResource(
							context.getResources(), face);
					if (bitmap != null) {
						if (small) {
							int rawHeigh = bitmap.getHeight();
							int rawWidth = bitmap.getHeight();
							int newHeight = 10;
							int newWidth = 10;
							// 计算缩放因子
							float heightScale = ((float) newHeight) / rawHeigh;
							float widthScale = ((float) newWidth) / rawWidth;
							// 新建立矩阵
							Matrix matrix = new Matrix();
							matrix.postScale(heightScale, widthScale);
							// 设置图片的旋转角度
							// matrix.postRotate(-30);
							// 设置图片的倾斜
							// matrix.postSkew(0.1f, 0.1f);
							// 将图片大小压缩
							// 压缩后图片的宽和高以及kB大小均会变化
							bitmap = Bitmap.createBitmap(bitmap, 0, 0,
									rawWidth, rawHeigh, matrix, true);
						}
						ImageSpan localImageSpan = new ImageSpan(context,
								bitmap, ImageSpan.ALIGN_BOTTOM);
						value.setSpan(localImageSpan, k, m,
								Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
					}
				}
			}
		}

		return value;
	}

	/**
	 * 解释消息XML，返回消息对象
	 * 
	 * @param str_xml
	 * @return
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	public static EntityMsg getEntityMessageFromXML(String str_xml) {

		EntityMsg entMsg = null;

		// 通过判断是否含有指定的标签，来决定消息的类型
		if (str_xml.contains("<gif>")) {
			entMsg = new EntityMsgGif();
		} else if (str_xml.contains("<voice>")) {
			entMsg = new EntityMsgVoice();
		} else if (str_xml.contains("<image>")) {
			entMsg = new EntityMsgImage();
		} else {
			entMsg = new EntityMsgText();
		}

		// InputStream xmlInStream = new
		// ByteArrayInputStream(str_xml.getBytes());
		//
		// XmlPullParser pull = Xml.newPullParser();
		//
		// pull.setInput(xmlInStream, "utf-8");
		//
		// int type = pull.getEventType();
		//
		// while (type != XmlPullParser.END_DOCUMENT) {
		//
		// switch (type) {
		// case XmlPullParser.START_DOCUMENT:
		// entMsg.setAllMessage(str_xml);
		// break;
		// case XmlPullParser.START_TAG:
		//
		// if ("message".equals(pull.getName())) {
		// entMsg.setYouUID(getMessageHiid(pull.getAttributeValue(
		// null, "to")));
		// entMsg.setTheMessageID(pull.getAttributeValue(null, "id"));
		// } else if ("body".equals(pull.getName())) {
		// entMsg.setBody(pull.nextText());
		// } else if ("MyExtension".equals(pull.getName())) {
		//
		// } else if ("uhead".equals(pull.getName())) {
		// entMsg.setUhead(pull.nextText());
		// } else if ("name".equals(pull.getName())) {
		// entMsg.setName(pull.nextText());
		// } else if ("local_image_path".equals(pull.getName())) {
		// entMsg.setLocal_image_path(pull.nextText());
		// } else if ("image".equals(pull.getName())) {
		// entMsg.setImage(pull.nextText());
		// } else if ("voice".equals(pull.getName())) {
		// entMsg.setVoice(pull.nextText());
		// } else if ("gif".equals(pull.getName())) {
		// entMsg.setGif(pull.nextText());
		// } else if ("local_voice_path".equals(pull.getName())) {
		// entMsg.setLocal_voice_path(pull.nextText());
		// }
		// break;
		// case XmlPullParser.END_DOCUMENT:
		//
		// break;
		// }
		// type = pull.next();
		// }
		return entMsg;
	}

	/**
	 * 提供一个文件名，得到asset目录下的图片 bitmap
	 * 
	 * @param fileName
	 * @return
	 */
	public static Bitmap getImageFromAssetsFile(String fileName) {
		Bitmap image = null;
		AssetManager am = MainApplication.getInstance().getAssets();
		try {
			InputStream is = am.open(fileName);
			image = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return image;

	}

	/**
	 * @Description
	 * @param name
	 */
	public void playMusic(String name) {
		MediaPlayer mMediaPlayer = getMediaPlayer();
		try {
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.stop();
			}
			mMediaPlayer.reset();
			mMediaPlayer.setDataSource(name);
			mMediaPlayer.prepare();
			mMediaPlayer.start();
			mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
				public void onCompletion(MediaPlayer mp) {

				}
			});

		} catch (Exception e) {

			L.e(e.getMessage());

		}

	}

	/**
	 * 停止播放
	 */
	public void playStop() {

		MediaPlayer mMediaPlayer = getMediaPlayer();
		if (mMediaPlayer.isPlaying()) {
			mMediaPlayer.stop();
		}
	}

	public String beautifulDistance(String oldDistance) {

		Double dis = Double.valueOf(oldDistance);
		if (dis >= 0) {

			return new BigDecimal(dis).setScale(2, BigDecimal.ROUND_HALF_UP)
					+ "km";

			// } else if (dis > 1000) {
			// return ">1000km";
		} else {
			return "未知";
		}

	}

	public String beautifulDateTime(String oldDateTime) {

		try {
			Date d1 = df.parse(oldDateTime);
			long l_d = (System.currentTimeMillis() - d1.getTime())
					/ (1000 * 60);

			if (l_d < 15) {

				return "刚刚";

			} else if (l_d >= 15 && l_d < 60) {

				return l_d + "分钟前";

			} else if (l_d >= 60 && l_d < 1440) {

				return (l_d / 60) + "小时前";

			} else if (l_d >= 1440 && l_d < 10080) {

				return (l_d / 1440) + "天前";

			} else {

				return "1星期前";
			}

		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return "1星期前";
		}
	}

	public int getSexBackground(String sex) {

		int s = 0;

		try {
			s = Integer.valueOf(sex);
		} catch (Exception e) {
			s = 0;
		}

		switch (s) {
		case 1:
			return R.drawable.sex1;
		case 2:
			return R.drawable.sex2;
		case 3:
			return R.drawable.sex3;
		case 4:
			return R.drawable.sex4;
		case 5:
			return R.drawable.sex5;
		case 6:
			return R.drawable.sex6;
		case 7:
			return R.drawable.sex7;
		case 8:
			return R.drawable.sex8;
		case 9:
			return R.drawable.sex9;
		case 10:
			return R.drawable.sex10;
		default:
			return R.drawable.sex1;

		}
	}

	/**
	 * 根据事个XML消息体。判断返回个消息对象
	 * 
	 * @param XMLBody
	 * @return
	 */
	public EntityMsg getWhichEntityMsgByXMLBody(String XMLBody) {

		EntityMsg entMsg = null;

		// 通过判断是否含有指定的标签，来决定消息的类型
		if (XMLBody.contains("<gif>")) {

			entMsg = new EntityMsgGif();

		} else if (XMLBody.contains("<voice>")) {

			entMsg = new EntityMsgVoice();

		} else if (XMLBody.contains("<image>")) {

			entMsg = new EntityMsgImage();

		} else {

			entMsg = new EntityMsgText();

		}

		return entMsg;
	}

	public String getSexNameBySexID(String sexID) {
		// 1:男,2:女,3:1,4:0,5:0.5,6:T,7:P,8:H,9:Ts,10:Bi

		int sexid = -1;

		try {
			sexid = Integer.valueOf(sexID);
		} catch (Exception e) {
			sexid = -1;
		}

		switch (sexid) {
		case 1:
			return "男";
		case 2:
			return "女";
		case 3:
			return "1";
		case 4:
			return "0";
		case 5:
			return "0.5";
		case 6:
			return "T";
		case 7:
			return "P";
		case 8:
			return "H";
		case 9:
			return "Ts";
		case 10:
			return "Bi";
		default:
			return "男";
		}
	}

	public String getDateTimeNow() {

		return df.format(new Date());
	}

	/**
	 * 返回时间差-分钟
	 * 
	 * @param dt1
	 *            现在时间
	 * @param dt2
	 *            上个时间
	 * @return
	 */
	public Long getDateDiff(String dt1, String dt2) {
		try {
			Date d1 = df.parse(dt1);
			Date d2 = df.parse(dt2);
			long diff = d1.getTime() - d2.getTime();
			// long days = diff / (1000 * 60 * 60 * 24);
			// long hours = (diff - days * (1000 * 60 * 60 * 24))/ (1000 * 60 *
			// 60);
			long minutes = diff / 60000;

			Log.i("dt", "现在时间：" + dt1 + "          上个时间：" + dt2);
			Log.i("minutes", minutes + "");

			return minutes;
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return (long) 0;
		}

	}

	public Boolean getDateDiff1(String dt1, String dt2) {
		try {
			Date d1 = df.parse(dt1);
			Date d2 = df.parse(dt2);
			long diff = d1.getTime() - d2.getTime();
			// long days = diff / (1000 * 60 * 60 * 24);
			// long hours = (diff - days * (1000 * 60 * 60 * 24))/ (1000 * 60 *
			// 60);
			long minutes = diff / 60000;

			Log.i("dt", "现在时间：" + dt1 + "          上个时间：" + dt2);
			Log.i("minutes", minutes + "");
			if (minutes > 10) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 用来判断服务是否运行.
	 * 
	 * @param context
	 * @param className
	 *            判断的服务名字
	 * @return true 在运行 false 不在运行
	 */
	public boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}
}
